//
//  TimeLineView.m
//  CultureTrade
//
//  Created by SZFT1 on 16/1/5.
//  Copyright (c) 2016年 cheng.zongxin. All rights reserved.
//

#import "TimeLineView.h"
#import "TipView.h"
#import "TimeLineChart.h"
#import "TimeChartPoint.h"
#import "NSString+Extension.h"
#import "TimeModel.h"
#import "TimeViewModel.h"

#define Scale_factory 0.8
#define kPointCount 242
#define kTopMargin 10

@interface TimeLineView () 
{
    UIView *_mainboxView; // k线图控件
    UIView *_moveOneView;   // 十字线
    UIView *_moveTwoView;
    TipView *_tipView;  //  悬浮提示窗
    UILabel *_lastTag;
    
    UIPinchGestureRecognizer *_pinchGesture; //捏合手势
    UILongPressGestureRecognizer *_longPressGestureRecognizer; //长按手势
    UIPanGestureRecognizer *_panGesture; //左右拖动
    CGPoint _currentPoint;    // 手指当前坐标
    
    NSMutableArray *_leftLabelArr;
    UILabel *_startDateLab;  // 5个时间点
    UILabel *_startDateLab1;
    UILabel *_startDateLab2;
    UILabel *_endDateLab;
    UILabel *_endDateLab1;
    
    TimeLineChart *_timeLineChart; // K线图
    TimeChartPoint *_timeChartPoint;  // 点坐标对象
    
    NSMutableArray *_pointArray;
    NSMutableArray *_models;
    
    NSTimer *mTimer;
    NSThread* mThread;
}
@end

@implementation TimeLineView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    [self initialization];
    [self addView];
    return self;
}

- (void)initialization
{
    self.backgroundColor = [UIColor blackColor];
    _pointArray = [NSMutableArray array];
    _timeChartPoint = [[TimeChartPoint alloc] init];
    self.font = [UIFont systemFontOfSize:9];
    _leftLabelArr = [NSMutableArray array];
    //    self.lineWidth = 1.0f;
    finishUpdateBlock = ^(id self){
        if (![[NSThread currentThread] isMainThread]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // 更UI
                [self updateInterface];
            });
        }else{
            [self updateInterface];
        }
    };
    
}

- (void)loadData{
    [TimeViewModel requestTimeDataWithSymbol:[Global shareInstance].quoteModel.Symbol exchange:[Global shareInstance].quoteModel.Exchange block:^(NSMutableArray *timeArray) {
        _models = timeArray;
        _pointArray = [_timeChartPoint PointsTransFromModels:_models innerFrame:_mainboxView.frame];
        finishUpdateBlock(self);
    }];
}

- (void)viewWillApper
{
    [self startTimer];
}

- (void)viewWillDisapper
{
    [self stopTimer];
}

- (void)startTimer // 30秒刷一次
{
    if (mTimer == nil) { // 30秒刷一次
        mTimer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:30.0f target:self selector:@selector(processEvent) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:mTimer forMode:NSDefaultRunLoopMode];
        
    }
}

- (void)stopTimer
{
    [mTimer invalidate];
    mTimer = nil;
    
}

- (void)processEvent
{
    NSThread* mThrad = [[NSThread alloc] initWithTarget:self selector:@selector(loadData) object:nil];
    [mThrad start];
}


#pragma mark -
#pragma mark 添加视图
- (void)addView
{
    if (_mainboxView==nil)
    {
        _mainboxView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopMargin, self.frame.size.width-20 ,self.frame.size.height-25)];
        _mainboxView.backgroundColor = [UIColor ColorWithHexString:@"#222222" withAlpha:1];
        _mainboxView.userInteractionEnabled = YES;
        [self addSubview:_mainboxView];
        // 添加手指捏合手势，放大或缩小k线图
//        _pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(touchBoxAction:)];
//        [_mainboxView addGestureRecognizer:_pinchGesture];
        // 添加长按手势，用于显示十字线
        _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] init];
        [_longPressGestureRecognizer addTarget:self action:@selector(gestureRecognizerHandle:)];
        [_longPressGestureRecognizer setMinimumPressDuration:0.3f];
        [_longPressGestureRecognizer setAllowableMovement:50.0];
        [_mainboxView addGestureRecognizer:_longPressGestureRecognizer];
        // left swipe
//        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panBoxAction:)];
//        [_mainboxView addGestureRecognizer:_panGesture];
        
    }

    // 左边标签
    CGFloat padRealValue = _mainboxView.frame.size.height / 5;
    _leftLabelArr = [NSMutableArray arrayWithCapacity:6];
    for (int i = 0; i < 6; i++) {
        CGFloat y = _mainboxView.frame.size.height-padRealValue * i;
        UILabel *leftTag = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 40, y - 15 + kTopMargin, 38, 30)];
        leftTag.text = [[NSString alloc] initWithFormat:@"%.2f",00.00];
        leftTag.textColor = [UIColor ColorWithHexString:@"#cccccc" withAlpha:1];
        leftTag.font = self.font;
        leftTag.textAlignment = NSTextAlignmentCenter;
        leftTag.backgroundColor = [UIColor clearColor];
        [self addSubview:leftTag];
        [_leftLabelArr addObject:leftTag];
    }
    
    //  最后一个时间线
    if (!_lastTag) {
        _lastTag = [[UILabel alloc] init];
        _lastTag.textColor = [UIColor ColorWithHexString:@"#cccccc" withAlpha:1];
        _lastTag.font = self.font;
        _lastTag.textAlignment = NSTextAlignmentCenter;
        _lastTag.backgroundColor = [UIColor blackColor];
        ViewBorder(_lastTag, [UIColor whiteColor], 1);
        ViewRadius(_lastTag, 3);
        [self addSubview:_lastTag];
        
        
        
        [_lastTag mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(self.frame.size.width - 40));
            make.size.mas_equalTo(CGSizeMake(38, 15));
        }];
        
        [_lastTag sizeToFit];
    }
    
    
    
    // 添加平均线值显示
//    CGRect mainFrame = _mainboxView.frame;
    
    // 把显示开始结束日期放在成交量的底部左右两侧
    // 显示开始日期控件
    CGFloat mainboxW = _mainboxView.frame.size.width - 80;
    if (_startDateLab==nil)
    {
        _startDateLab = [[UILabel alloc] initWithFrame:CGRectMake(_mainboxView.frame.origin.x
                                                                  , _mainboxView.frame.origin.y+_mainboxView.frame.size.height
                                                                  , 50
                                                                  , 15)];
        _startDateLab.font = self.font;
        _startDateLab.text = @"06:00";
        _startDateLab.textColor = [UIColor ColorWithHexString:@"CCCCCC" withAlpha:1];
        _startDateLab.backgroundColor = [UIColor clearColor];
        [self addSubview:_startDateLab];
    }
    
    if (_startDateLab1==nil)
    {
        _startDateLab1 = [[UILabel alloc] initWithFrame:CGRectMake(mainboxW*0.25-25
                                                                  , _mainboxView.frame.origin.y+_mainboxView.frame.size.height
                                                                  , 50
                                                                  , 15)];
        _startDateLab1.font = self.font;
        _startDateLab1.text = @"08:15";
        _startDateLab1.textAlignment = NSTextAlignmentCenter;
        _startDateLab1.textColor = [UIColor ColorWithHexString:@"CCCCCC" withAlpha:1];
        _startDateLab1.backgroundColor = [UIColor clearColor];
        [self addSubview:_startDateLab1];
    }
    
    if (_startDateLab2==nil)
    {
        _startDateLab2 = [[UILabel alloc] initWithFrame:CGRectMake(mainboxW*0.5-25
                                                                   , _mainboxView.frame.origin.y+_mainboxView.frame.size.height
                                                                   , 50
                                                                   , 15)];
        _startDateLab2.font = self.font;
        _startDateLab2.text = @"10:30";
        _startDateLab2.textAlignment = NSTextAlignmentCenter;
        _startDateLab2.textColor = [UIColor ColorWithHexString:@"CCCCCC" withAlpha:1];
        _startDateLab2.backgroundColor = [UIColor clearColor];
        [self addSubview:_startDateLab2];
    }
    
    // 显示结束日期控件
    if (_endDateLab1==nil)
    {
        _endDateLab1 = [[UILabel alloc] initWithFrame:CGRectMake(mainboxW*0.75-25
                                                                , _startDateLab.frame.origin.y
                                                                , 50
                                                                , 15)];
        _endDateLab1.font = self.font;
        _endDateLab1.text = @"12:45";
        _endDateLab1.textAlignment = NSTextAlignmentCenter;
        _endDateLab1.textColor = [UIColor ColorWithHexString:@"CCCCCC" withAlpha:1];
        _endDateLab1.backgroundColor = [UIColor clearColor];
        [self addSubview:_endDateLab1];
    }
    
    // 显示结束日期控件
    if (_endDateLab==nil)
    {
        _endDateLab = [[UILabel alloc] initWithFrame:CGRectMake(mainboxW-25
                                                                , _startDateLab.frame.origin.y
                                                                , 50
                                                                , 15)];
        _endDateLab.font = self.font;
        _endDateLab.text = @"15:00";
        _endDateLab.textColor = [UIColor ColorWithHexString:@"CCCCCC" withAlpha:1];
        _endDateLab.backgroundColor = [UIColor clearColor];
        _endDateLab.textAlignment = NSTextAlignmentRight;
        [self addSubview:_endDateLab];
    }
    
    // 长按时的十字线条
    _moveOneView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 0.5)];
    _moveOneView.backgroundColor = [UIColor whiteColor];
    _moveOneView.hidden = YES;
    [self addSubview:_moveOneView];
    
    _moveTwoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0.5, CGRectGetMaxY(_mainboxView.frame))];
    _moveTwoView.backgroundColor = [UIColor whiteColor];
    _moveTwoView.hidden = YES;
    [self addSubview:_moveTwoView];
    
    _tipView = [[TipView alloc] initWithFrame:CGRectMake(self.frame.size.width - 65, 0, 60, 75)];
    _tipView.layer.borderWidth = 0.5f;
    _tipView.layer.borderColor = [UIColor whiteColor].CGColor;
    _tipView.hidden = YES;
    [self addSubview:_tipView];
    
    _timeLineChart = [[TimeLineChart alloc] initWithFrame:(CGRect){CGPointZero,_mainboxView.frame.size}];
    [_mainboxView addSubview:_timeLineChart];
    
}


#pragma mark 长按就开始生成十字线
-(void)gestureRecognizerHandle:(UILongPressGestureRecognizer*)longResture
{
    MYLog(@"%ld",(long)longResture.state);
    
    if (_pointArray.count == 0) return;  // 没有数据不加载十字线和框图
    
    if (longResture.state == UIGestureRecognizerStateBegan) {
        CGPoint currentPoint = [longResture locationInView:_mainboxView];
        MYLog(@"UIGestureRecognizerStateBegan = %@",NSStringFromCGPoint(currentPoint));
        
        // 手指是否越过边线
        
        CGRect oneFrame = _moveOneView.frame;
        oneFrame.origin.y = currentPoint.y;
        _moveOneView.frame = oneFrame;
        
        CGRect twoFrame = _moveTwoView.frame;
        twoFrame.origin.x = currentPoint.x;
        _moveTwoView.frame = twoFrame;
        
        _moveOneView.hidden = NO;
        _moveTwoView.hidden = NO;
        _tipView.hidden = NO;
    }
    // 滑动过程中
    if (longResture.state == UIGestureRecognizerStateChanged) {
        CGPoint currentPoint = [longResture locationInView:_mainboxView];
        MYLog(@"UIGestureRecognizerStateChanged = %@",NSStringFromCGPoint(currentPoint));
        
        // 滑出边界
        CGRect mainFrame = _mainboxView.frame;
        CGFloat minX = mainFrame.origin.x;
        CGFloat maxX = mainFrame.size.width + minX;
        CGFloat minY = mainFrame.origin.y;
        CGFloat maxY = mainFrame.size.height + minY;
        
        if (currentPoint.x < minX || currentPoint.x > maxX || currentPoint.y < minY || currentPoint.y > maxY) {
            _moveOneView.hidden = YES;
            _moveTwoView.hidden = YES;
            return;
        }
        
        
        float oneUnit = (_mainboxView.frame.size.width - TIME_VIEW_RIGHT_SPACE) / _models.count;
        // 定位stock
        int theNum = currentPoint.x / oneUnit;
        if (theNum +1 > _pointArray.count) {
            theNum --;
        }
        
        // 画十字线
        CGRect oneFrame = _moveOneView.frame;
        oneFrame.origin.y = currentPoint.y;
        _moveOneView.frame = oneFrame;
        
        CGRect twoFrame = _moveTwoView.frame;
        twoFrame.origin.x = currentPoint.x;
        _moveTwoView.frame = twoFrame;
        
        // 根据手指长按的位置更改tipView位置不被手指遮盖
        if (currentPoint.x < _tipView.frame.size.width){
            _tipView.frame = CGRectMake(self.frame.size.width - 65, 0, 60, 75);
        }
        if (currentPoint.x > _tipView.frame.origin.x) {
            CGRect frame = _tipView.frame;
            frame.origin.x = 0;
            _tipView.frame = frame;
        }
        
        if (theNum < _pointArray.count) { // 数组没那么长
            // 显示左上角数值视图
            MYLog(@"theNum stock  = %d",theNum);
            [self showTipViewWithChartPoint:_models[theNum]];
        }
    }
    
    if (longResture.state == UIGestureRecognizerStateEnded) {
        CGPoint currentPoint = [longResture locationInView:_mainboxView];
        MYLog(@"UIGestureRecognizerStateEnded = %@",NSStringFromCGPoint(currentPoint));
        _moveOneView.hidden = YES;
        _moveTwoView.hidden = YES;
        _tipView.hidden = YES;
    }
}

- (void)showTipViewWithChartPoint:(TimeModel *)timeModel
{
    NSString *time = [timeModel.sDate componentsSeparatedByString:@"T"].lastObject;
    _tipView.date.text = [NSString stringWithFormat:@"时间:%@",time];
    _tipView.openPrice.text = [NSString stringWithFormat:@"成交:%d",timeModel.Vol];
    _tipView.highestPrice.text = [NSString stringWithFormat:@"涨跌:%f",timeModel.High];
    _tipView.lowestPrice.text = [NSString stringWithFormat:@"均价:%f",timeModel.Low];
    _tipView.closePrice.text = [NSString stringWithFormat:@"成交量:%f",timeModel.Open];
    _tipView.hidden = NO;
}


//finishUpdateBlock回调updateInterface
- (void)updateInterface
{
    [self updateChartView];              // 必须先移除旧的view，加载新的view
    _timeLineChart.pointArray = _pointArray; // set方法重绘
    [self updateLabelText];                 // 更新新的view上的文本
    [self drawNowPriLable];             // 更新最后一个文本

};

- (void)updateChartView
{
    [_timeLineChart removeFromSuperview];
    _timeLineChart = [[TimeLineChart alloc] initWithFrame:(CGRect){CGPointZero,_mainboxView.frame.size}];
//    _lineChart.kLineWidth = _chartPoint.kLineWidth;
    [_mainboxView addSubview:_timeLineChart];
    //    _chartPoint.intervalSpace = 0.5;
    
}

- (void)updateLabelText
{
    float maxPrice = _timeChartPoint.maxPrice;
    float minPrice = _timeChartPoint.minPrice;
    
    for (int i = 0; i< _leftLabelArr.count; i ++) {
        UILabel *leftTag = _leftLabelArr[i];
        
        CGFloat intervalValue = (maxPrice - minPrice) / (_leftLabelArr.count - 1);
        leftTag.text = [[NSString alloc] initWithFormat:@"%f",(intervalValue*i+minPrice)];
    }
    
    // 时间轴转换
    TimeModel *firstModel = _models.firstObject;
    TimeModel *lastModel = _models.lastObject;
    
    NSString *startTimeSource = firstModel.sDate;
    NSString *endTimeSource = lastModel.sDate;
    
    NSString *startTime = [startTimeSource stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    NSString *endTime = [endTimeSource stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *startDate = [formatter dateFromString:startTime];
    NSDate *endDate = [formatter dateFromString:endTime];
    
    NSTimeInterval timePadding = ([endDate timeIntervalSince1970] - [startDate timeIntervalSince1970])/4;
    
    NSTimeInterval time1sp = [startDate timeIntervalSince1970];
    NSTimeInterval time2sp = time1sp + timePadding;
    NSTimeInterval time3sp = time1sp + timePadding*2;
    NSTimeInterval time4sp = time1sp + timePadding*3;
    NSTimeInterval time5sp = [endDate timeIntervalSince1970];
    
    NSDate *time1Date = [NSDate dateWithTimeIntervalSince1970:time1sp];
    NSDate *time2Date = [NSDate dateWithTimeIntervalSince1970:time2sp];
    NSDate *time3Date = [NSDate dateWithTimeIntervalSince1970:time3sp];
    NSDate *time4Date = [NSDate dateWithTimeIntervalSince1970:time4sp];
    NSDate *time5Date = [NSDate dateWithTimeIntervalSince1970:time5sp];
    
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"HH:mm"];
    
    NSString *time1Str = [formatter1 stringFromDate:time1Date];
    NSString *time2Str = [formatter1 stringFromDate:time2Date];
    NSString *time3Str = [formatter1 stringFromDate:time3Date];
    NSString *time4Str = [formatter1 stringFromDate:time4Date];
    NSString *time5Str = [formatter1 stringFromDate:time5Date];
    
    _startDateLab.text = time1Str;
    _startDateLab1.text = time2Str;
    _startDateLab2.text = time3Str;
    _endDateLab1.text = time4Str;
    _endDateLab.text = time5Str;
}



- (void)drawNowPriLable{
    
    TimeChartPoint *lastPoint = [_pointArray lastObject];
    
    CGFloat y = lastPoint.nowPriPoint.y;
    
    TimeModel *lastTime = [_models lastObject];
    
    // 检测非正常坐标数字时返回0
    if (isnan(y)) y = 0;
    
    [_lastTag mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(y);
    }];
    
    _lastTag.text = [[NSString alloc] initWithFormat:@"%f",lastTime.Close];
}




@end
